import wsgiref.handlers
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from dgrWalking import SavedMapPoint

''' 
This little module will manage the task of walking in real time
By taking a post from dgr when a destination is chosen the handler will add a task to the queue to execute at
the time that it takes to walk to the next destination

Once it has done this, we can set a flag in the db to allow the bot to walk again.
In this manner the walk will occur in real time

TODO: 1. think about allowing the route steps to be logged in this manner
      2. ensure that a db flag can be set and is read by the dgrWalking module

'''

class WalkHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('counters.html',
                                                {'counters': Counter.all()}))

    def post(self):
        key = self.request.get('key')

        # Add the task to the default queue.
        taskqueue.add(url='/worker', params={'key': key})

        self.redirect('/')

class WalkWorker(webapp.RequestHandler):
    def post(self): # should run at most 1/s
        key = self.request.get('key')
        def txn():
            counter = Counter.get_by_key_name(key)
            if counter is None:
                counter = Counter(key_name=key, count=1)
            else:
                counter.count += 1
            counter.put()
        db.run_in_transaction(txn)

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
        ('/', CounterHandler),
        ('/worker', CounterWorker),
    ]))

if __name__ == '__main__':
    main()